package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.oa.dao.system.CompanyDao;
import jsyf.oa.dao.system.RegionDao;
import jsyf.oa.entity.system.RegionEntity;
import jsyf.oa.facade.system.RegionFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class RegionService implements RegionFacade {
    @Autowired
    private RegionDao dao;

    @Autowired
    private CompanyDao companyDao;

    @Override
    public String save(String jsonData) {
        RegionEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), RegionEntity.class);
        if (StringUtils.isEmpty(entity.getId()) || "0".equals(entity.getId())) {
            dao.add(entity);
        } else {
            RegionEntity oldEntity = dao.getEntityById(entity.getId());
            oldEntity.setName(entity.getName());
            oldEntity.setParentId(entity.getParentId());
            oldEntity.setCompanyId(entity.getCompanyId());
            oldEntity.setSortNo(entity.getSortNo());
            oldEntity.setDelFlag(entity.getDelFlag());
            dao.update(oldEntity);
        }
        return entity.getId();
    }


    @Override
    public Boolean delById(String id) {
        return dao.delById(id) > 0;
    }

    @Override
    public boolean removeById(String id) {
        return dao.removeById(id) > 0;
    }

    @Override
    public List<JSONObject> getTreeNodes() {
        List<JSONObject> nodeList = new ArrayList<>();
        JSONObject nodeRoot = new JSONObject();
        nodeRoot.put("id", "0");
        nodeRoot.put("pId", "-1");
        nodeRoot.put("name", "自定义区域");
        nodeRoot.put("type", "root");
        nodeRoot.put("dataId", "0");
        nodeRoot.put("isParent", true);
        nodeRoot.put("open", true);
        nodeList.add(nodeRoot);
        List<JSONObject> companyList = companyDao.getJSONListByCondition(" AND DEL_FLAG = 0  ORDER BY SORT_NO", new Object[]{});
        for (int i = 0; i < companyList.size(); i++) {
            JSONObject node = companyList.get(i);
            if (StringUtils.isEmpty(node.getString("parentId")) || "0".equals(node.getString("parentId"))) {
                node.put("pId", "0");
            } else {
                node.put("pId", node.getString("parentId"));
            }
            node.put("type", "company");
            node.put("companyId", node.getString("id"));
            node.put("isParent", true);
            nodeList.add(node);
        }
        List<JSONObject> list = dao.getJSONListByCondition(" AND DEL_FLAG = 0  ORDER BY SORT_NO", new Object[]{});
        for (int i = 0; i < list.size(); i++) {
            JSONObject node = list.get(i);
            if (StringUtils.isEmpty(node.getString("parentId")) || "0".equals(node.getString("parentId"))) {
                node.put("pId", node.getString("companyId"));
            } else {
                node.put("pId", node.getString("parentId"));
            }
            node.put("companyId", node.getString("companyId"));
            node.put("type", "region");
            nodeList.add(node);
        }

        return nodeList;
    }

    @Override
    public JSONObject getRegionByUserId(String userId) {
        StringBuffer sql = new StringBuffer();
        sql.append(" AND ID IN (");
        sql.append(" SELECT REGION_ID FROM T_SYS_USER_2_REGION WHERE 1=1");
        sql.append(" AND USER_ID =?)");
        JSONObject result = new JSONObject();
        JSONObject newRegionCity = new JSONObject();
        JSONObject newRegionCounty = new JSONObject();
        //查询大区
        List<JSONObject> regionCity = dao.getJSONListByCondition(sql.toString()
                + " AND PARENT_ID ='0'", new Object[]{userId});
        for (int i = 0; i < regionCity.size(); i++) {
            JSONObject jsonCity = regionCity.get(i);
            newRegionCity.put("regionCityId", jsonCity.getString("id"));
            newRegionCity.put("regionCityName", jsonCity.getString("name"));
        }
        //查询区域
        String regionCountyIds = "";
        String regionCountyNames = "";
        List<JSONObject> regionCounty = dao.getJSONListByCondition(sql.toString()
                + " AND NOT PARENT_ID ='0'", new Object[]{userId});
        for (int i = 0; i < regionCounty.size(); i++) {
            JSONObject jsonCounty = regionCounty.get(i);
            String regionCountyId = jsonCounty.getString("id");
            regionCountyIds += regionCountyId + ",";
            String regionCountyName = jsonCounty.getString("name");
            regionCountyNames += regionCountyName + ",";
        }
        regionCountyIds = regionCountyIds.substring(0, regionCountyIds.length() - 1);
        regionCountyNames = regionCountyNames.substring(0, regionCountyNames.length() - 1);
        newRegionCounty.put("regionCountyIds", regionCountyIds);
        newRegionCounty.put("regionCountyNames", regionCountyNames);
        //组合json
        result.put("regionCity", newRegionCity);
        result.put("regionCounty", newRegionCounty);
        return result;
    }

    @Override
    public List<JSONObject> getBigRegionListByCompanyId(String companyId) {
        return dao.getJSONListByCondition(" AND COMPANY_ID = ? AND PARENT_ID = '0' AND DEL_FLAG = 0 ", new String[]{companyId});
    }

    @Override
    public List<JSONObject> getBigRegionListByUserId(String userId, String isBigRegion) {
        StringBuilder sbCondition = new StringBuilder();
        sbCondition.append(" AND DEL_FLAG = 0 ");
        if (isBigRegion.equals("1")) {
            //大区
            sbCondition.append(" AND PARENT_ID = '0' ");
        } else if (isBigRegion.equals("0")) {
            //小区
            sbCondition.append(" AND PARENT_ID <> '0' ");
        }
        sbCondition.append(" AND ID IN( ");
        sbCondition.append(" SELECT REGION_ID FROM T_SYS_USER_2_REGION WHERE USER_ID = ? ");
        sbCondition.append(" ) ");
        return dao.getJSONListByCondition(sbCondition.toString(), new String[]{userId});
    }

    @Override
    public List<JSONObject> getSmallRegionListByParentId(String parentId) {
        return dao.getJSONListByCondition(" AND PARENT_ID = ? AND DEL_FLAG = 0 ", new String[]{parentId});
    }

    @Override
    public Boolean sort(String regionIds) {
        return dao.sort(regionIds);
    }

    @Override
    public String getRegionByWreport(String userId, String roleName) {
        if ("大客户经理".equals(roleName) || "区域经理".equals(roleName)) {
            StringBuilder condition = new StringBuilder();
            List<Object> sqlArgs = new ArrayList<Object>();
            condition.append(" AND ID IN ( ");
            condition.append(" SELECT REGION_ID FROM T_SYS_USER_2_REGION");
            condition.append(" WHERE 1=1 AND USER_ID =? )");
            switch (roleName) {
                case "区域经理":
                    condition.append(" AND PARENT_ID !='0' \n");
                    break;
                case "大客户经理":
                    condition.append(" AND PARENT_ID ='0' \n");
                    break;
                default:
                    break;
            }
            sqlArgs.add(userId);
            List<JSONObject> result = dao.getJSONListByCondition(condition.toString(), sqlArgs.toArray());
            if (result != null && result.size() > 0) {
                String roleNames = "";
                for (int i = 0; i < result.size(); i++) {
                    roleNames += "" + result.get(i).getString("name") + "/";
                }
                roleNames = roleNames.substring(0, roleNames.length() - 1);
                return roleNames;
            }
        }
        return null;
    }
}
